import Fastify from 'fastify';
import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
import { ApiResponse, ApiResultCode, IApiRequest, IApiRequestData, IApiResponse } from './defines';
import logger from './logger';


const logFile = path.join(__dirname, '../logs/fastify.log');
const logStream = fs.createWriteStream(logFile, { flags: 'a' });

const fastify = Fastify({
    logger: {
        level: 'info',
        transport: {
            target: 'pino/file',
            options: {
                destination: logFile
            }
        }
    }
});

const modules: Record<string, any> = {};

async function loadModules() {
    const modulesDir = path.join(__dirname, 'modules');
    const files = fs.readdirSync(modulesDir);

    for (const file of files) {
        if (!file.endsWith('.ts') && !file.endsWith('.js')) continue;
        const modName = path.basename(file, path.extname(file));
        const modPath = path.join(modulesDir, file);
        const modUrl = pathToFileURL(modPath).href; // ✅ 转换为 file:// URL
        const mod = await import(modUrl);
        modules[modName] = mod;

        logger.info(`Loaded module: ${modName}`);
    }

    logger.info('Loaded modules:%j', Object.keys(modules));
}

process.on('unhandledRejection', (reason, promise) => {
    logger.error('Unhandled Rejection:%s', reason);
    // console.error('Unhandled Rejection at:', promise, 'reason:', reason);
    // 可选择退出进程
    // process.exit(1);
});

process.on('uncaughtException', (err) => {
    logger.error('Uncaught Exception:%s', err.message);
    // console.error('Uncaught Exception:', err);
    // 可选择退出进程
    // process.exit(1);
});

async function start() {

    try {

        await loadModules();

        fastify.post('/api', async (req, reply): Promise<IApiResponse> => {
            const { m, f, d } = req.body as IApiRequest;
            const mod = modules[m];
            if (!mod)
                return ApiResponse.fail(ApiResultCode.NotFound, `Module ${m} not found`);
            // return reply.status(404).send({ error: `Module ${m} not found` });
            const fn = mod[f] as (data?: IApiRequestData) => Promise<IApiResponse>;
            if (!fn)
                return ApiResponse.fail(ApiResultCode.NotFound, `Function ${f} not found`);
            // return reply.status(404).send({ error: `Function ${f} not found` });

            try {
                return await fn(d);
            } catch (error: Error | any) {
                return ApiResponse.fail(ApiResultCode.InternalServerError, error?.message);
            }
        });

        fastify.listen({ port: 3000 });
        logger.info('Server listening on port 3000');


    } catch (err) {
        // console.error('启动错误', err);
        logger.error('启动错误:%s', err);
    }
}
// curl -X POST http://localhost:3000/api -H "Content-Type: application/json" -d '{"m":"user","f":"login","d":{"username":"admin","password":"123456"}}'


start();